import { Button, Progress, SliderSingleProps, message } from "antd";
import {
  ProForm,
  ProFormSelect,
  ProFormSlider,
  ProFormText,
  DrawerForm,
} from "@ant-design/pro-components";
import { useState, useEffect } from "react";
import MediaSelectDrawer from "@/pages/parameter-settings/components/MediaSelectDrawer";
import { createHighlights } from "@/services/api/api-intelligent-processing";
import { getSettingInfo } from "@/services/api/api-parameter-settings";

interface CompilationItem {
  id: string;
  name: string;
  videoUrl: string;
  createdTime: string;
}

interface MediaItem {
  id: string;
  name: string;
  full_path?: string;
  coverUrl?: string;
  duration?: number;
}

interface CompilationCreatorProps {
  visible: boolean;
  onClose: () => void;
  onCreate: (compilation: CompilationItem) => void;
  selectedFaceIds: [];
  folderId: number;
}

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

const marksTime: SliderSingleProps["marks"] = {
  0.5: "0.5秒",
  1: "1秒",
  1.5: "1.5秒",
  2: "2秒",
  2.5: "2.5秒",
  3: "3秒",
};
const marksVolume: SliderSingleProps["marks"] = {
  10: "10%",
  20: "20%",
  30: "30%",
  40: "40%",
  50: "50%",
  60: "60%",
  70: "70%",
  80: "80%",
  90: "90%",
  100: "100%",
};

const CompilationCreator = ({
  visible,
  onClose,
  onCreate,
  selectedFaceIds,
  folderId,
}: CompilationCreatorProps) => {
  const [creating, setCreating] = useState(false);
  const [progress, setProgress] = useState(0);
  const [form] = ProForm.useForm();
  const [settings, setSettings] = useState({
    transition_duration: 0.5,
    transition_effect: "淡入淡出",
    header_path: "",
    footer_path: "",
    bgm_path: "",
    bgm_volume: 0.3,
    image_duration: 3,
    available_transitions: [],
  });

  // 选择的媒体文件
  const [selectedMedia, setSelectedMedia] = useState<{
    introVideo?: MediaItem;
    outroVideo?: MediaItem;
    backgroundMusic?: MediaItem;
  }>({});

  // 控制抽屉显示状态
  const [drawerVisible, setDrawerVisible] = useState({
    introVideo: false,
    outroVideo: false,
    backgroundMusic: false,
  });

  // 获取设置数据
  const getSettingData = async () => {
    try {
      const res = await getSettingInfo();
      console.log("API返回数据:", res);

      // 从返回数据中提取highlight_config
      const highlightConfig = res.data?.highlight_config || {};
      const data = highlightConfig;

      setSettings({
        ...data,
        available_transitions: data.available_transitions || [],
      });

      // 设置表单值
      const formValues = {
        transition: data.transition_effect || "淡入淡出",
        transitionDuration: data.transition_duration || 0.5,
        musicVolume: (data.bgm_volume || 0.3) * 100, // 转换为百分比
      };

      console.log("设置表单值:", formValues, data);
      form.setFieldsValue(formValues);

      // 根据路径设置媒体项
      if (data.bgm_path) {
        setSelectedMedia((prev) => ({
          ...prev,
          backgroundMusic: {
            id: "1",
            name: data.bgm_path,
            full_path: data.bgm_path,
          },
        }));
      }
      if (data.header_path) {
        setSelectedMedia((prev) => ({
          ...prev,
          introVideo: {
            id: "2",
            name: data.bgm_path,
            full_path: data.header_path,
          },
        }));
      }
      if (data.footer_path) {
        setSelectedMedia((prev) => ({
          ...prev,
          outroVideo: {
            id: "3",
            name: data.bgm_path,
            full_path: data.footer_path,
          },
        }));
      }
    } catch (error) {
      console.error("Failed to fetch settings:", error);
      message.error("获取设置失败");
    }
  };

  useEffect(() => {
    if (visible) {
      getSettingData();
    }
  }, [visible]);

  const handleCreate = async (values: any) => {
    setCreating(true);
    setProgress(0);
    console.log(selectedFaceIds);

    const interval = setInterval(() => {
      setProgress((prev) => (prev >= 90 ? prev : prev + 10));
    }, 300);

    try {
      const res = await createHighlights({
        folder_id: folderId,
        face_group_ids: selectedFaceIds,
        // 添加媒体配置参数
        header_path: selectedMedia.introVideo?.full_path || "",
        footer_path: selectedMedia.outroVideo?.full_path || "",
        bgm_path: selectedMedia.backgroundMusic?.full_path || "",
        bgm_volume: (values.musicVolume || 50) / 100, // 转换回0-1范围
        transition_effect: values.transition || "淡入淡出",
        transition_duration: values.transitionDuration || 0.5,
      });

      const compilation = {
        name: values.name || "New Compilation",
      };

      setProgress(100);
      await waitTime(500);
      onCreate(compilation);
      return true; // Return true to close the drawer
    } catch (error) {
      message.error("创建集锦失败");
      return false; // Return false to keep the drawer open
    } finally {
      clearInterval(interval);
      setCreating(false);
    }
  };

  // 处理媒体选择
  const handleMediaSelect =
    (type: "introVideo" | "outroVideo" | "backgroundMusic") =>
    (item: MediaItem) => {
      console.log(item, selectedMedia);

      setSelectedMedia((prev) => ({
        ...prev,
        [type]: item,
      }));
      setDrawerVisible((prev) => ({ ...prev, [type]: false }));

      message.success(`${getMediaLabel(type)}已选择`);
    };

  const getMediaLabel = (type: string) => {
    switch (type) {
      case "backgroundMusic":
        return "背景音乐";
      case "introVideo":
        return "片头视频";
      case "outroVideo":
        return "片尾视频";
      default:
        return "";
    }
  };

  const renderMediaItem = (item: MediaItem | undefined) => {
    console.log(item);

    if (!item) return null;
    return (
      <div style={{ display: "flex", alignItems: "center", marginBottom: 8 }}>
        {item.full_path.match(/\.(mp4|mov|avi|mkv)$/i) ? (
          <span
            role="img"
            aria-label="video"
            style={{ fontSize: 24, marginRight: 8 }}
          >
            🎬
          </span>
        ) : (
          <span
            role="img"
            aria-label="music"
            style={{ fontSize: 24, marginRight: 8 }}
          >
            🎵
          </span>
        )}
        <span style={{ fontSize: 14 }}>{item.name}</span>
      </div>
    );
  };

  return (
    <>
      <DrawerForm
        title="创建视频集锦"
        width={600}
        open={visible}
        form={form}
        onOpenChange={(open) => {
          if (!open) {
            onClose();
          }
        }}
        onFinish={handleCreate}
        submitter={{
          render: (props, defaultDoms) => {
            return [
              <Button key="cancel" onClick={onClose}>
                取消
              </Button>,
              <Button
                key="submit"
                type="primary"
                loading={creating}
                onClick={() => props.submit()}
              >
                创建
              </Button>,
            ];
          },
        }}
      >
        <ProFormText
          name="name"
          label="集锦名称"
          placeholder="请输入集锦名称"
          rules={[{ required: true, message: "请输入集锦名称" }]}
        />

        <ProFormSelect
          name="transition"
          label="转场效果"
          valueEnum={settings.available_transitions.reduce((acc, curr) => {
            acc[curr] = curr;
            return acc;
          }, {} as Record<string, string>)}
          placeholder="请选择转场效果"
        />

        <ProFormSlider
          name="transitionDuration"
          label="转场时长(秒)"
          min={0.1}
          max={3}
          step={0.1}
          marks={marksTime}
          tooltip={{ formatter: (value) => `${value}秒` }}
        />

        <div style={{ marginBottom: 16 }}>
          <div style={{ marginBottom: 8, fontWeight: 500 }}>片头视频</div>
          {renderMediaItem(selectedMedia.introVideo)}
          <Button
            onClick={() =>
              setDrawerVisible((prev) => ({ ...prev, introVideo: true }))
            }
            style={{ marginTop: 8 }}
          >
            {selectedMedia.introVideo ? "更换片头视频" : "选择片头视频"}
          </Button>
        </div>

        <div style={{ marginBottom: 16 }}>
          <div style={{ marginBottom: 8, fontWeight: 500 }}>片尾视频</div>
          {renderMediaItem(selectedMedia.outroVideo)}
          <Button
            onClick={() =>
              setDrawerVisible((prev) => ({ ...prev, outroVideo: true }))
            }
            style={{ marginTop: 8 }}
          >
            {selectedMedia.outroVideo ? "更换片尾视频" : "选择片尾视频"}
          </Button>
        </div>

        <div style={{ marginBottom: 16 }}>
          <div style={{ marginBottom: 8, fontWeight: 500 }}>背景音乐</div>
          {renderMediaItem(selectedMedia.backgroundMusic)}
          <Button
            onClick={() =>
              setDrawerVisible((prev) => ({ ...prev, backgroundMusic: true }))
            }
            style={{ marginTop: 8 }}
          >
            {selectedMedia.backgroundMusic ? "更换背景音乐" : "选择背景音乐"}
          </Button>
        </div>

        <ProFormSlider
          name="musicVolume"
          label="音乐音量"
          min={0}
          max={100}
          marks={marksVolume}
          tooltip={{ formatter: (value) => `${value}%` }}
        />

        {creating && (
          <div style={{ marginTop: 24 }}>
            <Progress percent={progress} status="active" />
            <div style={{ textAlign: "center", marginTop: 8 }}>
              正在创建集锦...
            </div>
          </div>
        )}
      </DrawerForm>

      {/* 三个媒体选择抽屉 */}
      <MediaSelectDrawer
        visible={drawerVisible.introVideo}
        onClose={() =>
          setDrawerVisible((prev) => ({ ...prev, introVideo: false }))
        }
        onSelect={handleMediaSelect("introVideo")}
        mediaType="video"
      />
      <MediaSelectDrawer
        visible={drawerVisible.outroVideo}
        onClose={() =>
          setDrawerVisible((prev) => ({ ...prev, outroVideo: false }))
        }
        onSelect={handleMediaSelect("outroVideo")}
        mediaType="video"
      />
      <MediaSelectDrawer
        visible={drawerVisible.backgroundMusic}
        onClose={() =>
          setDrawerVisible((prev) => ({ ...prev, backgroundMusic: false }))
        }
        onSelect={handleMediaSelect("backgroundMusic")}
        mediaType="audio"
      />
    </>
  );
};

export default CompilationCreator;
